package net.mingsoft.cms.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author: kaiwang
 * @description: http请求
 * @date: 2022/5/10 11:05
 */
@Slf4j
@Component
public class HttpRestTemplateService {
    @Autowired
    private RestTemplate restTemplate;

    public JSONObject doPost(String url, Map<String, Object> params){
        return doPost(url,params,null);
    }

    public JSONObject doPost(String url, Map<String, Object> params,Map<String,String> headerMap) {
        long s = System.currentTimeMillis();
        try {
            log.info("post请求三方入参:请求地址:{},参数:{},head:{}",url,JSONObject.toJSONString(params),headerMap.toString());
            HttpHeaders requestHeaders = new HttpHeaders();
            if(headerMap!=null&&headerMap.size()>0) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    requestHeaders.add(entry.getKey(), entry.getValue());
                }
            }
            requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, requestHeaders);
            ResponseEntity<String> responseResult = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            log.info("post请求耗时{},返回结果{}",(System.currentTimeMillis()-s),responseResult.getBody());
            if(responseResult.getBody() != null){
                log.info("HttpService:"+ JSON.toJSONString(responseResult.getBody().replaceAll("\\\\","")));
                return JSONObject.parseObject(responseResult.getBody().replaceAll("\\\\",""));
            }else {
                log.info("HttpService:为null");
                return null;
            }
        } catch (Exception e){
            log.error("请求三方接口异常url{}",url,e);
            return null;
        }
    }

    public JSONObject doGet(String url){
        long st = System.currentTimeMillis();
        try {
            String postForObject = restTemplate.getForObject(url, String.class);
            log.info("get请求耗时:{},url:{},postForObject:{}, ",(System.currentTimeMillis()-st),url,postForObject);
            if(postForObject != null){
                return JSONObject.parseObject(postForObject);
            }else {
                return null;
            }
        } catch (Exception e){
            log.error("get请求三方接口异常url{},耗时{}",url,(System.currentTimeMillis() - st),e);
            return null;
        }
    }
}
